package com.lizhen.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @author lizhen
 */
public class HttpClient {

    /**
     * @author lizhen
     */
    public HttpClient() {
    }

    /**
     * @author lizhen
     */
    public static void main(String[] args) {
        HttpClient httpClient = new HttpClient();
        httpClient.httpGet();
    }

    /**
     * @author lizhen
     */
    private void httpGet() {
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("http://httpbin.org/get");
        // Create a custom response handler
        ResponseHandler<String> responseHandler = response -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity httpEntity = response.getEntity();
                return httpEntity != null ? EntityUtils.toString(httpEntity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        };
        try {
            String responseBody = closeableHttpClient.execute(httpGet, responseHandler);

            System.out.println("Executing request " + httpGet.getRequestLine());
            System.out.println(responseBody);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
